package com.kisyou.索引.查询速度Test;

import com.mysql.cj.jdbc.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;

public class InsertData {
    private static final String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final Random rand = new Random(20230504);

    private static String randomString(int minSize, int maxSize) {
        StringBuilder sb = new StringBuilder();
        int size = rand.nextInt(maxSize - minSize) + minSize;

        for (int i = 0; i < size; i++) {
            int idx = rand.nextInt(chars.length());
            char ch = chars.charAt(idx);
            sb.append(ch);
        }

        return sb.toString();
    }


    public static void main(String[] args) throws SQLException {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setUser("debian-sys-maint");
        mysqlDataSource.setPassword("co7lI761pHOFy9gx");
        mysqlDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/jdbc_mysql?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai");

        int recordSize = 5_0000;
        int sizePerBatch = 500;
        int batchSize = recordSize / sizePerBatch;

        try (Connection c = mysqlDataSource.getConnection()) {
            c.setAutoCommit(false);

            String sql = "insert into users (name_1, name_2) values (?, ?)";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                // 一个 PreparedStatement，绑定不同的数据，完成不同数据的插入，为了提升插入效率
                for (int i = 0; i < batchSize; i++) {
                    for (int j = 0; j < sizePerBatch; j++) {
                        String name = randomString(3, 5);
                        ps.setString(1, name);
                        ps.setString(2, name);
                        ps.executeUpdate();
                    }

                    System.out.println("提交了第 " + i + " 批数据");
                    c.commit();
                }
            }
        }
    }
}
